package com.ruoyi.student.service;

import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.student.domain.StudentBaodao;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.domain.PhdAdmissionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
public class PhdImportAsyncService {

    @Autowired
    private IStudentBaodaoService studentBaodaoService;

    @Autowired
    private IStudentInfoService studentInfoService;

    @Autowired
    private IPhdAdmissionInfoService phdAdmissionInfoService;

    private final Map<String, ImportProgress> importProgressMap = new ConcurrentHashMap<>();

    /**
     * 异步执行博士批量导入（仅处理typeStatus为"1"且shuoshiboshi为"2"的报到记录）
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public Future<ImportResult> doImport(String batchNo) {
        ImportProgress progress = new ImportProgress();
        progress.setBatchNo(batchNo);
        progress.setStatus("处理中");
        progress.setProgress(0);
        importProgressMap.put(batchNo, progress);
        System.out.println("开始处理博士批量导入");
        try {
            // 1. 查询符合条件的博士报到记录
            // 过滤条件：typeStatus为"1" 且 shuoshiboshi为"2"（博士标识）
            StudentBaodao query = new StudentBaodao();
            query.setTypeStatus("1");
            query.setShuoshiboshi("2");
            List<StudentBaodao> phdBaodaoList = studentBaodaoService.selectStudentBaodaoList(query);
            System.out.println(phdBaodaoList );
            int total = phdBaodaoList.size();
            System.out.println(total);
            progress.setTotal(total);
            importProgressMap.put(batchNo, progress);
            System.out.println("cnm");
            if (total == 0) {
                progress.setStatus("完成");
                progress.setProgress(100);
                importProgressMap.put(batchNo, progress);
                return new AsyncResult<>(new ImportResult(batchNo, 0, "无符合条件的博士报到数据（typeStatus=1且shuoshiboshi=2）"));
            }

            // 2. 批量查询已存在的博士信息
            List<StudentInfo> existingPhds = studentInfoService.getAllStudentInfoList(new StudentInfo());
            System.out.println("rnm");
            Set<String> existingPhdIds = existingPhds.stream()
                    .filter(s -> s.getStudentId() != null)
                    .map(StudentInfo::getStudentId)
                    .collect(Collectors.toSet());

            // 3. 收集需要查询的博士学号，通过IPhdAdmissionInfoService获取数据
            Set<String> needQueryXh = phdBaodaoList.stream()
                    .map(StudentBaodao::getStudentNum)
                    .filter(xh -> !existingPhdIds.contains(xh))
                    .collect(Collectors.toSet());

            // 批量查询并转为Map（学号 -> 博士录取信息）
            Map<String, PhdAdmissionInfo> xhToImportMap = new HashMap<>();
            if (!needQueryXh.isEmpty()) {
                PhdAdmissionInfo queryImport = new PhdAdmissionInfo();
                queryImport.setStudentIdList(new ArrayList<>(needQueryXh));
                List<PhdAdmissionInfo> importList = phdAdmissionInfoService.selectBatchByStudentIds(queryImport);
                System.out.println(importList);
                for (PhdAdmissionInfo importData : importList) {
                    String xh = importData.getStudentId();
                    if (xhToImportMap.containsKey(xh)) {
                        throw new RuntimeException("博士学号" + xh + "存在多条导入数据，请检查");
                    }
                    xhToImportMap.put(xh, importData);
                }
            }

            // 4. 构建批量插入列表（使用学院专业代码填充）
            List<StudentInfo> insertList = new ArrayList<>(100);
            int successCount = 0;

            for (int i = 0; i < phdBaodaoList.size(); i++) {
                StudentBaodao baodao = phdBaodaoList.get(i);
                String phdNum = baodao.getStudentNum();

                // 跳过已存在的博士
                if (existingPhdIds.contains(phdNum)) {
                    updateProgress(progress, i + 1, total, successCount);
                    continue;
                }

                // 校验导入数据是否存在
                PhdAdmissionInfo importData = xhToImportMap.get(phdNum);
                if (importData == null) {
                    throw new RuntimeException("博士学号" + phdNum + "未找到对应录取数据");
                }

                // 构建博士信息（学院专业使用代码填充）
                StudentInfo phdInfo = new StudentInfo();
                phdInfo.setId(IdUtils.fastSimpleUUID());
                phdInfo.setStudentId(importData.getStudentId()); // 学号
                phdInfo.setStudentName(importData.getName()); // 姓名

                // 基本信息映射
                phdInfo.setStudentSex(importData.getGenderCode()); // 性别（代码）
                phdInfo.setStudentCnum(importData.getIdNumber()); // 身份证号
                phdInfo.setStudentSjh(importData.getContactInfo()); // 联系电话

                // 学业信息映射（使用代码填充学院和专业）
                phdInfo.setStudentYx(importData.getAdmissionCollegeCode()); // 院系（学院名称）
                phdInfo.setStudentZy(importData.getAdmissionMajorCode()); // 专业（专业名称）
                phdInfo.setStudentYjfx(importData.getAdmissionResearchDirectionName()); // 研究方向
                phdInfo.setStudentDs(importData.getAdmissionSupervisorName()); // 导师姓名
                phdInfo.setStudentXxfs(importData.getAdmissionStudyMethod()); // 学习方式
                phdInfo.setStudentXwlx("博士"); // 学位类型

                insertList.add(phdInfo);
                successCount++;

                // 每100条批量插入一次
                if (insertList.size() >= 100) {
                    studentInfoService.batchInsert(insertList);
                    insertList.clear();
                }

                // 更新进度
                updateProgress(progress, i + 1, total, successCount);
            }

            // 插入剩余数据
            if (!insertList.isEmpty()) {
                studentInfoService.batchInsert(insertList);
            }

            // 完成处理
            progress.setStatus("完成");
            progress.setProgress(100);
            progress.setSuccessCount(successCount);
            importProgressMap.put(batchNo, progress);

            return new AsyncResult<>(new ImportResult(batchNo, successCount, "博士数据导入成功"));

        } catch (Exception e) {
            progress.setStatus("失败");
            progress.setErrorMsg(e.getMessage());
            importProgressMap.put(batchNo, progress);
            return new AsyncResult<>(new ImportResult(batchNo, 0, "博士数据导入失败：" + e.getMessage()));
        }
    }

    /**
     * 查询导入进度
     */
    public ImportProgress getImportProgress(String batchNo) {
        return importProgressMap.getOrDefault(batchNo, new ImportProgress());
    }

    /**
     * 更新进度信息
     */
    private void updateProgress(ImportProgress progress, int current, int total, int successCount) {
        progress.setProgress((int) ((current * 1.0 / total) * 100));
        progress.setSuccessCount(successCount);
        importProgressMap.put(progress.getBatchNo(), progress);
    }

    // 导入进度内部类
    public static class ImportProgress {
        private String batchNo;
        private String status; // 处理中/完成/失败
        private int progress; // 0-100
        private int total; // 总条数
        private int successCount; // 成功条数
        private String errorMsg; // 错误信息

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public int getProgress() { return progress; }
        public void setProgress(int progress) { this.progress = progress; }
        public int getTotal() { return total; }
        public void setTotal(int total) { this.total = total; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getErrorMsg() { return errorMsg; }
        public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; }
    }

    // 导入结果内部类
    public static class ImportResult {
        private String batchNo;
        private int successCount;
        private String msg;

        public ImportResult(String batchNo, int successCount, String msg) {
            this.batchNo = batchNo;
            this.successCount = successCount;
            this.msg = msg;
        }

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getMsg() { return msg; }
        public void setMsg(String msg) { this.msg = msg; }
    }
}
